//
//  XLDoctor
//
//  Created by longma on 2018/7/31.
//  Copyright © 2018年 XLH. All rights reserved.
//

#import "UserManager.h"

@interface UserManager ()


@end

@implementation UserManager

/**
 单例
 */
+ (instancetype)shared{
    static UserManager *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[UserManager alloc] init];
    });
    return instance;
}

- (void)saveUserInfo:(NSDictionary *)data {
    
    if(data){
        UserModel *userModel = [UserModel yy_modelWithDictionary:data];
        if(self.userToken){
            //已登录
            userModel.token = self.userToken;
        }else{
            //未登录
            WCBDHelper.shared.isNeedUpdateHealthData = true;
        }
        
        NSError *error;
        NSData *userData = [NSKeyedArchiver archivedDataWithRootObject:userModel requiringSecureCoding:YES error:&error];
        if (error) {
            NSLog(@"MJLog=======================NSKeyedArchiver archive failed with error:%@",error);
        }
        [MJUIUserDeFault setObject:userData forKey:Login_User];
        self.userModel = userModel;
        self.userToken = userModel.token;

    }else{
        [WCBDHelper.shared removeFiles]; //删除所有文件表
        HealthHelper.shared.homePatientList = nil;
        
        [MJUIUserDeFault setObject:nil forKey:Login_User];
        self.userModel = nil;
        self.userToken = nil;
    }
}

- (void)saveUserInfoModel:(UserModel *)userModel {
    
    if(self.userToken){
        userModel.token = self.userToken;
    }
    
    NSError *error;
    NSData *userData = [NSKeyedArchiver archivedDataWithRootObject:userModel requiringSecureCoding:YES error:&error];
    if (error) {
        NSLog(@"MJLog=======================NSKeyedArchiver archive failed with error:%@",error);
    }
    [MJUIUserDeFault setObject:userData forKey:Login_User];
    self.userModel = userModel;
    self.userToken = userModel.token;
}

- (void)initUserInfo {
    
    NSData *userData = [MJUIUserDeFault objectForKey:Login_User];
    NSError *error;
    UserModel *userModel = [NSKeyedUnarchiver unarchivedObjectOfClasses:[NSSet setWithArray:@[[UserModel class],[NSString class],[NSNumber class]]] fromData:userData error:&error];
    if (error) {
        NSLog(@"MJLog=======================NSKeyedArchiver unarchive failed with error:%@",error);
    }
    self.userModel = userModel;
    self.userToken = userModel.token;
}

- (void)logout{
    [MJUIUserDeFault setObject:@"0" forKey:SetPassword_Open];
    [MJUIUserDeFault setObject:@"0" forKey:NotesGuide_Open];
    [MJUIUserDeFault setObject:@"0" forKey:MatchCodeNumber_Open];
    
    [UserManager.shared saveUserInfo:nil];
    AppDelegate *appDelegate=(AppDelegate *)[[UIApplication sharedApplication]delegate];
    [appDelegate initRootViewController];
}

@end
